import type { AstroIntegration } from "astro";
import { exec } from "node:child_process"
import { mkdir, readFile, writeFile } from "node:fs/promises";

const _NORMAL_CHANGELOG_LINE_COUNT_ = 12
const _NORMAL_WIKI_CHANGELOG_LINE_COUNT_ = 12

function getContentFromLineCount(lineCount: number, content: string) {
  return content.split("\n").slice(0, lineCount).join("\n")
}

async function getChildProcessExec(cmd: string) {
  await new Promise<void>((resolve) => {
    const cp = exec(cmd, (error, stdout, stderr) => {
      console.log(stdout);
    })

    cp.on("close", () => {
      resolve()
    })
  })
}

async function generateWiki(lineCount?: number) {
  const filePath = ".cache/changelog/guide-wiki-changelog.md"
  await mkdir(".cache/changelog", { recursive: true })
  await writeFile(filePath, "")
  await getChildProcessExec('auto-changelog -c src/template/wiki/guide-wiki-changelog/config.json')
  if (lineCount) {
    await writeFile(
      filePath,
      getContentFromLineCount(lineCount, await readFile(filePath, "utf-8"))
    );
  }
}

async function generateNormal(lineCount?: number) {
  const filePath = ".cache/changelog/guide-changelog.md"
  await mkdir(".cache/changelog", { recursive: true })
  await writeFile(filePath, "")
  await getChildProcessExec('auto-changelog -c src/template/wiki/guide-changelog/config.json')
  if (lineCount) {
    await writeFile(
      filePath,
      getContentFromLineCount(lineCount, await readFile(filePath, "utf-8"))
    );
  }
}

async function generate() {
  await Promise.all([
    generateWiki(_NORMAL_WIKI_CHANGELOG_LINE_COUNT_),
    generateNormal(_NORMAL_CHANGELOG_LINE_COUNT_)
  ])
}

export default function (): AstroIntegration {
  return {
    name: "WikiGuideChangelogGenerate",
    hooks: {
      "astro:server:start": async () => {
        await generate()
      },
      "astro:build:start": async () => {
        if (process.env.NODE_ENV === "production") await generate()
      }
    }
  }
}